import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function POST(request: Request) {
  try {
    const { 
      playerId, 
      swordTier, 
      crystalTier, 
      buhcTier, 
      potionTier, 
      npotTier, 
      smpTier 
    } = await request.json();

    if (!playerId) {
      return NextResponse.json(
        { error: '缺少玩家ID' },
        { status: 400 }
      );
    }

    // 查找玩家是否存在
    const player = await prisma.player.findUnique({
      where: { id: Number(playerId) }
    });

    if (!player) {
      return NextResponse.json(
        { error: '玩家不存在' },
        { status: 404 }
      );
    }

    // 更新玩家段位
    const updatedPlayer = await prisma.player.update({
      where: { id: Number(playerId) },
      data: {
        swordTier: swordTier !== undefined ? Number(swordTier) : player.swordTier,
        crystalTier: crystalTier !== undefined ? Number(crystalTier) : player.crystalTier,
        buhcTier: buhcTier !== undefined ? Number(buhcTier) : player.buhcTier,
        potionTier: potionTier !== undefined ? Number(potionTier) : player.potionTier,
        npotTier: npotTier !== undefined ? Number(npotTier) : player.npotTier,
        smpTier: smpTier !== undefined ? Number(smpTier) : player.smpTier
      }
    });

    // 解析地区信息
    let player_region = updatedPlayer.region;
    let player_region_id = null;
    let player_region_color = null;
    let player_is_blacklisted = false;
    
    // 检查是否为黑名单
    if (player_region && player_region.includes('[blacklisted]')) {
      player_is_blacklisted = true;
      player_region = player_region.replace('[blacklisted]', '');
    }
    
    // 解析地区ID和颜色
    if (player_region && player_region.includes('|')) {
      const parts = player_region.split('|');
      player_region = parts[0];
      player_region_id = parts[1];
      player_region_color = parts[2];
    }

    const formattedPlayer = {
      ...updatedPlayer,
      id: updatedPlayer.id.toString(),
      region: player_region,
      region_id: player_region_id,
      region_color: player_region_color,
      is_blacklisted: player_is_blacklisted
    };

    return NextResponse.json({
      success: true,
      player: formattedPlayer
    });
  } catch (error) {
    console.error('Update tier error:', error);
    return NextResponse.json(
      { success: false, error: '更新段位失败' },
      { status: 500 }
    );
  }
} 